const log = require('./common');

function deepClone(obj){
    const cache = new WeakMap();

    function _deepClone(obj){
        if(obj === null || typeof obj !== 'object') return obj;
        if(cache.has(obj)) return cache.get(obj);

        const result = Array.isArray(obj) ? [] : {};
        cache.set(obj,result);  //因为对象是引用,所以先为空也无所谓

    
        for(let key in obj){
            if(obj.hasOwnProperty(key)){
                result[key] = _deepClone(obj[key])
            }
        }
    
        return result;
    }
 
    return _deepClone(obj)
}

let circ = { name: 'zjh', arr: [1,2,3] }
circ.sub = circ      //循环引用
circ.arr.push(circ); //循环引用

let clone_circ = deepClone(circ);

log(clone_circ)